#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
服务器同步管理器
解决内存中的服务器列表与腾讯云API不同步的问题
"""

import time
import logging
from typing import Dict, List, Set, Optional
from dataclasses import dataclass
from .task_distribution import LoadBalancer, Server, ServerStatus
from .tencent_hai_api import TencentHAIClient

logger = logging.getLogger(__name__)


@dataclass
class ServerSyncResult:
    """服务器同步结果"""
    added_servers: List[str]      # 新增的服务器ID
    removed_servers: List[str]    # 移除的服务器ID
    updated_servers: List[str]    # 更新的服务器ID
    sync_success: bool            # 同步是否成功
    error_message: Optional[str]  # 错误信息


class ServerSyncManager:
    """服务器同步管理器"""
    
    def __init__(self, load_balancer: LoadBalancer, hai_client: TencentHAIClient):
        self.load_balancer = load_balancer
        self.hai_client = hai_client
        self.last_sync_time = 0
        self.sync_interval = 30  # 30秒同步一次
        self.force_sync = False
        
    def sync_servers_from_tencent(self) -> ServerSyncResult:
        """
        从腾讯云API同步服务器列表到内存
        
        Returns:
            ServerSyncResult: 同步结果
        """
        try:
            logger.info("开始同步服务器列表...")
            
            # 1. 获取腾讯云实际实例列表
            tencent_instances = self.hai_client.list_instances()
            tencent_server_ids = {instance.instance_id for instance in tencent_instances}
            
            # 1.1. 获取HAI应用列表
            real_apps_status = self.hai_client.get_real_apps_status()
            if real_apps_status.get('success') and real_apps_status.get('data'):
                healthy_apps = real_apps_status['data'].get('healthy_app_list', [])
                for app_id in healthy_apps:
                    # 将HAI应用也作为服务器添加到负载均衡器
                    if app_id not in tencent_server_ids:
                        tencent_server_ids.add(app_id)
                        # 创建虚拟实例对象
                        from types import SimpleNamespace
                        app_instance = SimpleNamespace()
                        app_instance.instance_id = app_id
                        app_instance.region = "ap-beijing"  # 默认地域
                        app_instance.gpu_type = "basic"     # 默认GPU类型
                        app_instance.status = "RUNNING"
                        tencent_instances.append(app_instance)
            
            # 2. 获取内存中的服务器列表
            memory_server_ids = set(self.load_balancer.servers.keys())
            
            # 3. 计算差异
            added_servers = list(tencent_server_ids - memory_server_ids)
            removed_servers = list(memory_server_ids - tencent_server_ids)
            
            logger.info(f"同步发现: 新增{len(added_servers)}个, 移除{len(removed_servers)}个服务器")
            
            # 4. 添加新服务器到内存
            for instance in tencent_instances:
                if instance.instance_id in added_servers:
                    # 为HAI应用设置正确的endpoint
                    if hasattr(instance, 'instance_id') and instance.instance_id.startswith('app-'):
                        # HAI应用的endpoint
                        endpoint = f"http://{instance.instance_id}.hai.tencentcloud.com:8080"
                    else:
                        # HAI实例的endpoint
                        endpoint = f"http://{instance.instance_id}.hai.tencentcloud.com"
                    
                    server = Server(
                        server_id=instance.instance_id,
                        region=instance.region,
                        gpu_type=instance.gpu_type,
                        status=ServerStatus.HEALTHY if instance.status == "RUNNING" else ServerStatus.UNHEALTHY,
                        created_time=time.time(),
                        endpoint=endpoint
                    )
                    self.load_balancer.add_server(server)
                    logger.info(f"同步添加服务器: {instance.instance_id} -> {endpoint}")
            
            # 5. 从内存移除不存在的服务器
            for server_id in removed_servers:
                self.load_balancer.remove_server(server_id)
                logger.info(f"同步移除服务器: {server_id}")
            
            # 6. 更新现有服务器状态
            updated_servers = []
            for instance in tencent_instances:
                if instance.instance_id in memory_server_ids:
                    # 更新服务器状态
                    new_status = ServerStatus.HEALTHY if instance.status == "RUNNING" else ServerStatus.UNHEALTHY
                    self.load_balancer.update_server_status(
                        instance.instance_id, 
                        new_status
                    )
                    updated_servers.append(instance.instance_id)
            
            self.last_sync_time = time.time()
            
            result = ServerSyncResult(
                added_servers=added_servers,
                removed_servers=removed_servers,
                updated_servers=updated_servers,
                sync_success=True,
                error_message=None
            )
            
            logger.info(f"服务器同步完成: 新增{len(added_servers)}, 移除{len(removed_servers)}, 更新{len(updated_servers)}")
            return result
            
        except Exception as e:
            logger.error(f"服务器同步失败: {e}")
            return ServerSyncResult(
                added_servers=[],
                removed_servers=[],
                updated_servers=[],
                sync_success=False,
                error_message=str(e)
            )
    
    def should_sync(self) -> bool:
        """检查是否需要同步"""
        if self.force_sync:
            return True
        
        current_time = time.time()
        return (current_time - self.last_sync_time) >= self.sync_interval
    
    def force_sync_now(self) -> ServerSyncResult:
        """强制立即同步"""
        self.force_sync = True
        result = self.sync_servers_from_tencent()
        self.force_sync = False
        return result
    
    def get_sync_status(self) -> Dict[str, any]:
        """获取同步状态"""
        return {
            "last_sync_time": self.last_sync_time,
            "sync_interval": self.sync_interval,
            "time_since_last_sync": time.time() - self.last_sync_time,
            "should_sync": self.should_sync(),
            "force_sync": self.force_sync
        }


class ServerSyncScheduler:
    """服务器同步调度器"""
    
    def __init__(self, sync_manager: ServerSyncManager):
        self.sync_manager = sync_manager
        self.running = False
        self.sync_thread = None
        
    def start(self):
        """启动同步调度器"""
        if self.running:
            return
        
        self.running = True
        import threading
        self.sync_thread = threading.Thread(target=self._sync_loop, daemon=True)
        self.sync_thread.start()
        logger.info("服务器同步调度器已启动")
    
    def stop(self):
        """停止同步调度器"""
        self.running = False
        if self.sync_thread:
            self.sync_thread.join(timeout=5)
        logger.info("服务器同步调度器已停止")
    
    def _sync_loop(self):
        """同步循环"""
        while self.running:
            try:
                if self.sync_manager.should_sync():
                    result = self.sync_manager.sync_servers_from_tencent()
                    if not result.sync_success:
                        logger.warning(f"同步失败: {result.error_message}")
                
                time.sleep(10)  # 每10秒检查一次
                
            except Exception as e:
                logger.error(f"同步循环异常: {e}")
                time.sleep(30)  # 出错时等待更长时间
